// pages/ad/index.js
const http = require('../../utils/http.js');
const app = getApp();
let timer = null;
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		id: null,
		videoUrl: null,
		isAudio: true,
		gg_time: wx.getStorageSync('userInfo').advert_time ? wx.getStorageSync('userInfo').advert_time : 30,
		isFinish: false,
		timer: null
	},
	//激励广告
	getAd() {
		var that = this;
		http.post('api/advert/get_advert', {
			en: 'ad_op_screen',
			li: 0
		}).then(res => {
			that.setData({
				// videoUrl: res.data[0].videourl
				videoUrl: 'http://www.w3school.com.cn/i/movie.mp4'
			})
			that.countDown()
		})
	},
	//退出广告
	closeGg() {
		this.setData({
			gg_time: 30,
			videoUrl: null,
			isAudio: true,
			isFinish: false
		})
		this.timer = null;
		this.onPlay(false);
		wx.navigateBack();
	},
	//音量控制
	changeAudio() {
		this.setData({
			isAudio: !this.data.isAudio
		})
	},
	//控制视频播放
	onPlay(on) {
		let videoplay = this.videoContext;
		if (on) {
			videoplay.play();
		} else {
			videoplay.pause();
		}
	},
	/**
	 * 倒计时
	 * @param endTime 结束日期+时间
	 * **/
	countDown() {
		var that = this;
		that.timer = setInterval(function() {
			// 倒计时结束
			if (that.data.gg_time <= 0) {
				that.setData({
					gg_time: 0,
					isFinish: true
				})
				//结束周期计时器
				clearInterval(that.timer);
				that.onPlay(false);
				return;
			}
			//同步显示
			that.setData({
				gg_time: that.data.gg_time - 1
			})
		}, 1000)
	},
	//领取奖励
	onReceive() {
		http.post('api/user/ac_task', {
			id: this.data.id
		}, 1).then(res => {
			wx.showModal({
				title: '',
				content: '领取成功~',
				complete: (d) => {
					if (d.confirm) {
						wx.navigateBack();
					}
				}
			})
		})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		this.videoContext = wx.createVideoContext('videoplay');
		this.getAd();
		this.setData({
			id: options.id
		})
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})